package com.sky.service.impl;
/*
@author sun
@date 24/07/15
@project IntelliJ IDEA
*/

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersConfirmDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private HttpMessageConverters messageConverters;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    // 订单搜索
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.pageQuery(ordersPageQueryDTO);

        // TODO 部分订单回显数据问题

        return new PageResult(page.getTotal(),page.getResult());
    }

    // 各个状态的订单数量统计  TODO  从 orderMapper 查出来 然后new OrderStatisticsVO() 在set进去封装
    public OrderStatisticsVO statistics() {
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    // 查询订单详情
    public OrderVO details(Long id) {
        Orders ordersDB = (Orders) orderMapper.getById(id); // 根据id查询订单

        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(ordersDB.getId()); // 查询该订单对应的菜品/套餐明细

        OrderVO orderVO = new OrderVO(); // 将该订单及其详情封装到OrderVO并返回
        BeanUtils.copyProperties(ordersDB,orderVO);
        orderVO.setOrderDetailList(orderDetailList);

        return orderVO;
    }

    // 接单
    public void orderConfirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders().builder().id(ordersConfirmDTO.getId()).status(Orders.CONFIRMED).build();
        orderMapper.update(orders);
    }

    // 拒单
    public void orderRejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        Orders ordersDB = (Orders) orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2(待接单)才可以拒单
        if (ordersDB == null || ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID){
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01)
            );
            log.info("申请退款:{}",refund);
        }

        // 拒单需要退款，根据订单id(更新订单状态，拒单原因，取消时间)
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    // 取消订单
    public void orderCancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id去查询订单
        Orders ordersDB = (Orders) orderMapper.getById(ordersCancelDTO.getId());

        // 支付状态
        Integer payStatus = ordersDB.getStatus();
        if (payStatus == 1){
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01)
            );
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    // 完成订单
    public void orderComplete(Long id) {

        Orders ordersDB = (Orders) orderMapper.getById(id); // 根据id查询订单

        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){// 校验订单是否存在，并且状态为4
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        };

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        orders.setStatus(Orders.COMPLETED);// 更新订单状态，状态转为完成中
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);
    }
    // 派送订单
    public void orderDelivery(Long id) {
        Orders ordersDB = (Orders) orderMapper.getById(id); // 根据id查询订单


        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)){ // 校验订单是否存在，并且状态为3
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());

        orders.setStatus(Orders.DELIVERY_IN_PROGRESS); // 更新订单状态，状态转为派送中

        orderMapper.update(orders);
    }
}
